package com.cetccloud.ap.proxy.processor.subscribe;

import com.alibaba.fastjson.JSON;
import com.cetccloud.ap.mapper.HttpSubscribeMapper;
import com.cetccloud.ap.mapper.pojo.HttpSubscribe;
import com.cetccloud.ap.proxy.channel.cossDomain.CrossDomainDispatcher;
import com.cetccloud.ap.proxy.common.ProxyContext;
import com.cetccloud.ap.proxy.processor.AbstractProcessor;
import com.cetccloud.ap.proxy.processor.exception.ProcessException;
import com.cetccloud.ap.proxy.processor.model.ProcessResult;
import com.cetccloud.ap.proxy.processor.subscribe.model.SubscribeHttpParam;
import com.cetccloud.ap.proxy.processor.subscribe.model.SubscribeHttpReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @ClassName SubscribeHttpProcessor
 * @Description TODO
 * @Author superz
 * @Date 2021/4/21 11:25
 * @Version 1.0
 **/
@Slf4j
@Component("subscribeHttpProcessor")
public class SubscribeHttpProcessor extends AbstractProcessor<SubscribeHttpParam, ProcessResult<SubscribeHttpReturn>> {

    @Autowired
    private HttpSubscribeMapper httpSubscribeMapper;

    @Override
    public Mono<ProcessResult<SubscribeHttpReturn>> process(SubscribeHttpParam subscribeHttpParam, ProxyContext context) {
        // todo 判断是否相同订阅请求
        try {
            // 订阅记录落库，响应生成的消息队列名称给请求端
            String topic = "subscribe." + System.currentTimeMillis();
            // todo 创建消息队列

            HttpSubscribe httpSubscribe = new HttpSubscribe();
            httpSubscribe.setZoneId((String) context.getAttribute(CrossDomainDispatcher.SRC_ZONE_ID));
            httpSubscribe.setUrl(subscribeHttpParam.getUrl());
            httpSubscribe.setMethod(subscribeHttpParam.getMethod());
            httpSubscribe.setHeader(JSON.toJSONString(subscribeHttpParam.getHeaders()));
            httpSubscribe.setBody(JSON.toJSONString(subscribeHttpParam.getBody()));
            httpSubscribe.setIncrement(JSON.toJSONString(subscribeHttpParam.getIncrement()));
            httpSubscribe.setTopic(topic);
            // 订阅状态,0: 创建, 1: 订阅中, 2: 结束
            httpSubscribe.setStatus((byte) 1);
            httpSubscribeMapper.insert(httpSubscribe);

            SubscribeHttpReturn subscribeHttpReturn = new SubscribeHttpReturn();
            subscribeHttpReturn.setTopic(topic);
            return Mono.just(ProcessResult.success().build(subscribeHttpReturn));
        } catch (Exception e) {
            log.error("SubscribeHttpProcessor process error", e);
            return Mono.error(new ProcessException(e));
        }
    }
}
